# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2023/1/23 22:32
@describe: 处理参数的第一步
"""
import traceback

from util.common import Common
from jsonpath import jsonpath
from swagger_parser import SwaggerParser


class ProcessedCase:

	def __init__(self, file: str):
		self.OPEN_API = Common().read_json_file(file)
		self.swagger = SwaggerParser(swagger_dict=self.OPEN_API)
		self.PATHS = dict(self.OPEN_API.get("paths", None))
		self.DEFINITIONS = dict(self.OPEN_API.get("definitions", None))
		self.PARAMS = {}
		self.PARAMS_DETAIL = {}
		self.CURRENT_DEFINITIONS = ""

	def analyze_data(self, data, result=""):
		"""递归的方式消除$ref引用"""
		if isinstance(data, dict):
			for k, v in data.items():
				self.analyze_data(v, result + "[\"%s\"]" % str(k))
		elif isinstance(data, list):
			for i in range(len(data)):
				self.analyze_data(data[i], result + f"[{i}]")
		else:
			if "$ref" in result.split('[')[-1]:
				exec(f"""{result}={jsonpath(self.DEFINITIONS, f'$.{data.split("/")[-1]}')}""")

	def params_operate(self):
		"""
		处理请求参数和请求参数明细
		:return: None
		"""
		for k, v in self.PATHS.items():
			# 判断method
			if jsonpath(v, "$.post"):
				self.PARAMS_DETAIL[k] = {"method": "post"}
			elif jsonpath(v, "$.get"):
				self.PARAMS_DETAIL[k] = {"method": "get"}
			else:
				raise ValueError("不支持的method类型")

			# PARAMS_DETAIL
			self.PARAMS_DETAIL[k].update(
				jsonpath(v, f"$.{self.PARAMS_DETAIL[k]['method']}")[0]
			)
			# 遍历所有parameters
			if self.PARAMS_DETAIL[k]["method"] == "post":
				try:
					if self.PARAMS_DETAIL[k].get("parameters", ""):
						self.CURRENT_DEFINITIONS = \
							jsonpath(self.PARAMS_DETAIL[k]["parameters"], "$...$ref")[-1].split("/")[-1]
						while isinstance(jsonpath(self.PARAMS_DETAIL[k]["parameters"], "$...$ref")[-1], str):
							self.analyze_data(
								self.PARAMS_DETAIL[k]["parameters"],
								f"self.PARAMS_DETAIL['{k}']['parameters']"
							)
				except Exception as e:
					raise ValueError(traceback.extract_stack(), e)

				# PARAMS
				self.PARAMS[k] = {}
				try:
					if self.PARAMS_DETAIL[k].get("parameters", ""):
						for para in self.PARAMS_DETAIL[k]["parameters"]:
							if para["in"] == "body":
								self.PARAMS[k] = self.swagger.definitions_example[self.CURRENT_DEFINITIONS]
				except Exception as e:
					raise ValueError(traceback.extract_stack(), e)
